package com.fg.cloud.common.kuaidi;

import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;

import org.apache.log4j.Logger;

import com.fg.cloud.common.kuaidi.utils.KuaidiConfig;



/**
 * 快递接口程序核心工具类
 * 用于访问快递100获取快递信息
 * 由于使用的免费版，所以添加了返回结果为html的形式，不能以json和xml方式。
 * 这里额外需要添加一个处理Html的功能，将内容转换为我们需要的
 * @author around
 * @date 2017-4-7
 */
public class KuaidiCore {
	
	/**
	 * 以Html形式获取快递信息
	 * @param urlcontext 拼接好参数的URL
	 * @return String
	 */
	public static String getDataByHtml(String urlcontext) {
		String content = null;
		try {
			URL url= new URL(urlcontext);
			URLConnection con = url.openConnection();
			InputStream urlStream = url.openStream();
			String type = URLConnection.guessContentTypeFromStream(urlStream);
			
			String charSet = null;
			if (type == null)
				type = con.getContentType();

			if (type == null || type.trim().length() == 0 || type.trim().indexOf("text/html") < 0)
				return "未找到订单编号";

			if(type.indexOf("charset=") > 0)
				charSet = type.substring(type.indexOf("charset=") + 8);
			else 
				charSet = "UTF-8";

			byte b[] = new byte[10000];
			int numRead = urlStream.read(b);
			content = new String(b, 0, numRead);
			while (numRead != -1) {
				numRead = urlStream.read(b);
				if (numRead != -1) {
					//String newContent = new String(b, 0, numRead);
					String newContent = new String(b, 0, numRead, charSet);
					content += newContent;
				}
			}
			urlStream.close();
		} catch (MalformedURLException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return content;
	}

	
	public static void main(String[] args) {
		String url = KuaidiConfig.getRequestURL("zhongtong", "460069550373", "desc");
		String content = getDataByHtml(url);
		System.out.println(url);
		System.out.println(content);
	}

}
